<?php

namespace Modules\Production\Repository;

use App\Services\UnitService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Base\Repository\BoxNumberRepository;
use Modules\Base\Repository\MaterialRepository;
use Modules\Production\Models\MaterialReturnPlanDetail;
use Modules\Production\Models\MaterialReturnPlanOrder;
use Modules\Production\Models\PickOrderDetailSplit;
use Modules\Production\Service\TaskScanService;

class MaterialReturnPlanOrderrRepository
{

    /**
     * 生产退料计划箱号扫描
     * @param $lotnum
     */
    static public function scanBy($lotnum){

        $returnData = [];
        //先查找拆箱表
        $splitPick = PickOrderDetailSplit::where('lot_num',$lotnum)->with(['pickdetail','order','material'])->get()->toArray();
        if(!empty($splitPick)){
            foreach ($splitPick as $item){

                $item['pickdetail']['qty']      = $item['qty'];
                $item['pickdetail']['lot_num']  = $item['lot_num'];
                $item['pickdetail']['split_qty']= 0;

                $row = $item['pickdetail'];
                $row['order']       = $item['order'];
                $row['material']    = $item['material'];

                $returnData[] = $row;
            }
        }

        if(empty($returnData)){
            $pick = PickOrderRepository::getPickOrderByLotNum($lotnum)->toArray();
            foreach ($pick as &$val){
                if($val['qty'] - $val['split_qty'] == 0){
                    continue;
                }
                $val['qty'] = $val['qty'] - $val['split_qty'];
                $returnData[] = $val;
            }
        }
        return $returnData;
    }

    /**
     * 生产退料计划提交处理
     * @param $postData
     */
    static public function storeBy($postData){

        if(!is_array($postData) || empty($postData)){
            throw new \Exception('提交参数不能为空！');
        }

        try{
            DB::beginTransaction();

            $returnPlanItem = [];
            $planOrderNo = UnitService::createDocno('SCTLJH');
            $returnPlanOrderId = (new MaterialReturnPlanOrder)->storeBy([
                'docno' => $planOrderNo
            ]);

            foreach ($postData as $val){
                //领料单信息
                $pickInfo = PickOrderRepository::getPickDetailWithOrderById($val['pick_detail_id']);

                $returnPlanItem[] = [
                    'order_id'      => $returnPlanOrderId,
                    'material_no'   => $pickInfo->material_no,
                    'source_lot_num'=> $val['lot_num'],
                    'lot_num'       => empty($val['to_lot_num']) ? $val['lot_num'] : $val['to_lot_num'],
                    'qty'           => $val['return_qty'],
                    'pick_order_no' => $pickInfo->order->docno,
                    'wms_code'      => $pickInfo->wms_code,
                    'location'      => $pickInfo->location,
                    'supplier_code' => $pickInfo->supplier_code,
                    'creator_id'    => Auth::guard(getGuardName())->id(),
                    'created_at'    => time(),
                    'updated_at'    => time(),
                ];

            }

            MaterialReturnPlanDetail::insert($returnPlanItem);

            $printData = self::getBoxPrintData($returnPlanItem,$planOrderNo);

            DB::commit();
            return $printData;

        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }

    /**
     * 获取打印数据
     * @param $returnPlanItem
     * @return mixed
     */
    static public function getBoxPrintData($returnPlanItem,$planOrderNo){

        foreach($returnPlanItem as &$val){
            $val['material']    = MaterialRepository::findMaterial($val['material_no']);
            $val['box']         = BoxNumberRepository::getBoxByCode($val['lot_num']);
            $val['production']  = PickOrderRepository::getProductionNoByPickNo($val['pick_order_no']);
            $val['print_date']  = date('Y-m-d');
            $val['return_plan_no']  = $planOrderNo;
        }

        return $returnPlanItem;
    }

    /**
     * 生产退料计划修改扫描
     * @param $lotnum
     * @return mixed
     */
    static public function getReturnPlanByLotnum($lotnum){
        $planOrder = MaterialReturnPlanDetail::where('lot_num',$lotnum)->with('order')->get()->toArray();
        if(empty($planOrder)){
            throw new \Exception('箱号不存在');
        }

        foreach ($planOrder as &$item){

            $pickOrder = PickOrderRepository::getProductionNoByPickNo($item['pick_order_no']);

            //生产工单信息
            $item['production_no'] = ProductionOrderRepository::getOrderById($pickOrder->producton_id);
            //子线物料信息
            $item['material'] = MaterialRepository::findMaterial($item['material_no']);
            //领料明细
            $item['pick_detail'] = 0;
        }

        return $planOrder;

    }

    /**
     * 根据子项箱号查询明细
     * @param $lotnum
     */
    static public function getOrderDetailByLotnum($lotnum){
        return MaterialReturnPlanDetail::where('lot_num',$lotnum)->with('order')->get();
    }

    /**
     * 根据子项id查询明细行和单据头
     * @param $lotnum
     */
    static public function getOrderDetailByDetailId($detailId){
        return MaterialReturnPlanDetail::with('order')->find($detailId);
    }


    /**
     * 生产退料计划修改提交
     * @param $postData
     * @return bool
     * @throws \Exception
     */
    static public function modifySubmit($postData){

        if(empty($postData)){
            throw new \Exception('提交数据为空');
        }

        try{
            DB::beginTransaction();

            foreach ($postData as $item){
                MaterialReturnPlanDetail::where('id',$item['plan_detail_id'])->update(['qty' => $item['modify_qty']]);
            }

            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }


    }

    /**
     * 根据生产退料单计划单id汇总子项
     * @param $orderId
     * @return mixed
     */
    static public function getGroupByListByOrderId($orderId){
        return MaterialReturnPlanDetail::select('material_no','pick_order_no','wms_code',DB::raw('sum(qty) as qty'))
            ->where('order_id',$orderId)
            ->groupBy('material_no','pick_order_no','wms_code')
            ->get();
    }

}
